# Maintainer: Konstantin Podsvirov <konstantin@podsvirov.pro>

_realname=helix
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=22.12
pkgrel=1
pkgdesc="A post-modern modal text editor (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64')
url="https://github.com/helix-editor/helix"
license=('MPL2')
makedepends=("${MINGW_PACKAGE_PREFIX}-rust"
             "${MINGW_PACKAGE_PREFIX}-mdbook")
options=('staticlibs' 'strip')
source=("$_realname-$pkgver.tar.gz::$url/archive/$pkgver.tar.gz"
        'helix.sh')
noextract=("${_realname}-${pkgver}.tar.gz")
sha256sums=('edae8af46401b45c3e71c38b4fa99f931c4458127978ccd1b29aaae79331d972'
            'c557a1e313586decf3d00fcf67e9a3f6139a2850b2e267b14d33e45636e84790')

prepare() {
  cd "${srcdir}"
  tar xf "${_realname}-${pkgver}.tar.gz" \
    --exclude=contrib/themes


  rm -rf "build-${MSYSTEM}" | true
  cp -r "${_realname}-${pkgver}" "build-${MSYSTEM}"
  cp -a "${_realname}-${pkgver}/runtime/themes" "build-${MSYSTEM}/contrib/themes"
  cd "${srcdir}/build-${MSYSTEM}"

  sed -i "s|hx|helix|g" contrib/completion/hx.*
  "${MINGW_PREFIX}/bin/cargo.exe" fetch \
    --locked
}

build() {
  msg "Cargo build for ${MSYSTEM}"
  cd "${srcdir}/build-${MSYSTEM}"

  "${MINGW_PREFIX}/bin/cargo.exe" build \
    --locked \
    --release

  msg "Build documentation"
  cd book

  "${MINGW_PREFIX}/bin/mdbook.exe" build
}

check() {
  cd "${srcdir}/build-${MSYSTEM}"

  "${MINGW_PREFIX}/bin/cargo.exe" test \
    --locked \
    --release
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"

  install -Dm755 "../${_realname}.sh" "${pkgdir}${MINGW_PREFIX}/bin/${_realname}"
  install -Dm755 "target/release/hx.exe" "${pkgdir}${MINGW_PREFIX}/lib/${_realname}/hx.exe"
  local runtime_dir="${pkgdir}${MINGW_PREFIX}/var/lib/${_realname}/runtime"
  mkdir -p "$runtime_dir/grammars"
  cp -r "runtime/queries" "$runtime_dir"
  cp -r "runtime/themes" "$runtime_dir"
  find "runtime/grammars" -type f -name '*.dll' -exec \
    install -Dm 755 {} -t "$runtime_dir/grammars" \;
  install -Dm644 runtime/tutor -t "$runtime_dir"
  cp -a "${runtime_dir}/" "${pkgdir}${MINGW_PREFIX}/lib/${_realname}/runtime/"
  install -Dm644 "contrib/completion/hx.bash" "${pkgdir}${MINGW_PREFIX}/share/bash-completion/completions/${_realname}"
  install -Dm644 "contrib/completion/hx.fish" "${pkgdir}${MINGW_PREFIX}/share/fish/vendor_completions.d/${_realname}.fish"
  install -Dm644 "contrib/completion/hx.zsh" "${pkgdir}${MINGW_PREFIX}/share/zsh/site-functions/_${_pkgname}"
  install -d "${pkgdir}${MINGW_PREFIX}/share/doc/${_realname}"
  cp -a "book/book" "${pkgdir}${MINGW_PREFIX}/share/doc/${_realname}/html"
  install -Dm644 "LICENSE" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}

